package com.atguigu.tingshu.order.strategy.impl;
import com.atguigu.tingshu.order.hander.OrderTradeNoHandler;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.google.common.collect.Lists;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * AlbumOrderTradeStrategy 专辑购买策略类
 *
 * @author Petrichor
 * @version 2024/01/05 20:46
 **/
@Service
@Slf4j
public class AlbumOrderTradeStrategy extends OrderTradeNoHandler implements OrderTradeStrategy {
    private final UserInfoFeignClient userInfoFeignClient;
    private final AlbumInfoFeignClient albumInfoFeignClient;
    private final RedisTemplate<String,String> redisTemplate;
    @Autowired
    public AlbumOrderTradeStrategy(UserInfoFeignClient userInfoFeignClient,
                                   AlbumInfoFeignClient albumInfoFeignClient,
                                   RedisTemplate<String, String> redisTemplate) {
        this.userInfoFeignClient = userInfoFeignClient;
        this.albumInfoFeignClient = albumInfoFeignClient;

        this.redisTemplate = redisTemplate;
    }

    /**
     * @description: 定义获取订单确认页面所需要的接口方法
     * @author Petrichor
     * @date 2024/1/5 20:43
     * @param tradeVo 订单确认对象
     * @return OrderInfoVo 订单对象
     **/
    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        // 付款项目类型Id
        Long itemId = tradeVo.getItemId();
        // 创建返回对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        //1、判断当前登录用户是否购买过该专辑，如果已经购买过就不需要再次进行购买
        Result<Boolean> paidAlbum = userInfoFeignClient.isPaidAlbum(itemId);
        Boolean isPaidAlbum = paidAlbum.getData();
        if(isPaidAlbum) {
            throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
        }
        //2、根据专辑的id查询专辑数据
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(itemId);
        AlbumInfo albumInfo = albumInfoResult.getData();
        //3、获取当前用户信息，判断用户是否为vip用户，并且判断vip是否已经过期。根据vip的情况使用专辑表中不同的打折价计算对应金额数据。
        Long userId = AuthContextHolder.getUserId();
        Result<UserInfo> userInfoByUserId = userInfoFeignClient.findUserInfoByUserId(userId);
        UserInfo userInfo = userInfoByUserId.getData();
        // 判断用户是否为vip用户，并且判断vip是否已经过期,并且vip折扣力度大于非vip折扣
        if(userInfo.getIsVip() == 1 &&
                userInfo.getVipExpireTime().after(new Date()) &&
                albumInfo.getVipDiscount().intValue()<albumInfo.getDiscount().intValue()) {
            // 是vip用户，同时vip用户没有过期 走vip优惠
            if(albumInfo.getVipDiscount().intValue() != -1 ) {
                // 如果vip的优惠折扣不是-1 说明有优惠
                BigDecimal vipDisCountPrice = albumInfo.getPrice()
                        .multiply(albumInfo.getVipDiscount())
                        .divide(new BigDecimal("10") , 2, RoundingMode.HALF_UP);
                // <5>减免总金额
                orderInfoVo.setDerateAmount(albumInfo.getPrice().subtract(vipDisCountPrice));
                // <6>订单总金额
                orderInfoVo.setOrderAmount(vipDisCountPrice);
            }else {
                // vip折扣-1 说明虽然没没过期 但优惠为零
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(albumInfo.getPrice());
            }
        }else {
            // 不是vip 或vip过期 走普通优惠
            // 走非vip打折价
            if(albumInfo.getDiscount().intValue() != -1 ) {
                // 需要进行打折
                BigDecimal disCountPrice = albumInfo.getPrice()
                        .multiply(albumInfo.getDiscount())
                        .divide(new BigDecimal("10") , 2, RoundingMode.HALF_UP);
                // <5>减免总金额
                orderInfoVo.setDerateAmount(albumInfo.getPrice().subtract(disCountPrice));
                // <6>订单总金额
                orderInfoVo.setOrderAmount(disCountPrice);

            }else {
                // 不需要进行打折
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(albumInfo.getPrice());
            }

        }
        // <3>付款项目类型: 1001-专辑 1002-声音 1003-vip会员
        orderInfoVo.setItemType(tradeVo.getItemType());
        // <4>订单原始金额
        orderInfoVo.setOriginalAmount(albumInfo.getPrice());

        // <7>订单明细列表
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(tradeVo.getItemId());
        orderDetailVo.setItemName(albumInfo.getAlbumTitle());
        orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
        orderDetailVo.setItemPrice(albumInfo.getPrice());
        orderInfoVo.setOrderDetailVoList(Arrays.asList(orderDetailVo));
        // <8>订单减免明细列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>() ;
        BigDecimal derateAmount = orderInfoVo.getDerateAmount();
        // 根据减免判断是否有列表
        if(derateAmount.intValue() > 0) {
            // 存在减免金额
            OrderDerateVo orderDerateVo = new OrderDerateVo() ;
            // 设置订单减免类型 此处是专辑折扣
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            // 设置减免金额
            orderDerateVo.setDerateAmount(derateAmount);
            // 备注
            orderDerateVo.setRemarks("专辑折扣减免");
            orderDerateVoList.add(orderDerateVo) ;
        }
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        // <1>交易号
        // <2>支付方式：1101-微信 1102-支付宝 1103-账户余额
        // <9>时间戳
        // <10>签名
        this.orderTradeNoHandle(orderInfoVo , redisTemplate);


        return orderInfoVo;
    }
    /**
     * @description: 定义获取对应的付款项目
     * @author Petrichor
     * @date 2024/1/5 20:44
     * @return 获取对应的付款项目
     **/
    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_ALBUM;
    }
}


